package org.autumn.review.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

//测试生产者消费者模型
@Slf4j
public class TestPC {
    public static void main(String[] args) {
        //容器
        Container container = new Container();
        //开启线程
        new Producer(container).start();
        new Consumer(container).start();
    }
}
//生成者
@Slf4j
class Producer extends Thread{
    Container container;

    public Producer(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 20; i++) {
            try {
                container.push(new Dog(i));
                Thread.sleep(100);
                log.info("生成了-->"+i+"只狗");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//消费者
@Slf4j
class Consumer extends Thread{
    Container container;

    public Consumer(Container container) {
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 1; i <=20 ; i++) {
            try {
                container.pop();
                Thread.sleep(1000);
                log.info("------------------>消费了-->"+i+"只狗");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
class Dog{
    int id;

    public Dog(int id) {
        this.id = id;
    }
}
//缓存区 Container
class Container{
    //容器
    List<Dog> dogs = new ArrayList<Dog>();
    //计数器
    int count = 0;
    //添加产品
    public synchronized void push(Dog dog) throws InterruptedException {
        //如果计数器等于10，等待
        if (count == 10){
            this.wait();
        }
        //添加到容器
        dogs.add(dog);
        //计数器++
        count++;
        //通知消费者消费
        this.notifyAll();
    }

    public synchronized Dog pop() throws InterruptedException {
        //如果计数器等于0，等待
        if (count == 0){
            this.wait();
        }

        count--;
        Dog dog = dogs.get(count);

        //通知生成者生产
        this.notifyAll();

        return dog;
    }

}

